import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class getTreeNode {
    /*              7

    *         5          10

    *    2       6     9    14

    * 1   3  null  1
    *
    * */

    TreeNode tn;
    public TreeNode getTn(){
        //第一层
        tn=new TreeNode(7);
        //第二层
        tn.left=new TreeNode(5);
        tn.right=new TreeNode(10);
        //第三层
        tn.left.left=new TreeNode(2);
        tn.left.right=new TreeNode(6);
        tn.right.left=new TreeNode(9);
        tn.right.right=new TreeNode(14);
        //第四层
        tn.left.left.left=new TreeNode(1);
        tn.left.left.right=new TreeNode(3);
        tn.left.right.right=new TreeNode(1);

        return tn;
    }
    //二叉树的层次遍历（关键在如何判断是否在同一层，这里使用一个队列来保存节点
    public void showTree(TreeNode treeNode){
            ArrayList<Integer> list = new ArrayList<>();
            if (treeNode==null){
                System.out.println("尼玛的是空的");
            }else {
                Queue<TreeNode> q=new LinkedList<>();
                q.add(treeNode);//先把根节点弄进去

                while (!q.isEmpty()){
                    int size=q.size();
                    List<Integer> currentRes = new LinkedList<>();
                    while (size>0){
                        TreeNode current=q.poll();
                        if (current==null){//该层遍历完了
                            continue;
                        }
                        currentRes.add(current.val);
                        //将这个节点的左右子节点加入队列，这样下一层的节点就加了进来
                        if (current.left != null) {
                            q.add(current.left);
                        }
                        if (current.right != null) {
                            q.add(current.right);
                        }
                        size--;
                    }
                    for (int i:currentRes){
                        list.add(i);//将该层的节点数据加入进去
                    }
                }
                for (int i:list){
                    System.out.print(i+" ");
                }
            }
    }

    public static void main(String[] args) {
        getTreeNode getTreeNode = new getTreeNode();
        TreeNode tn=getTreeNode.getTn();
        getTreeNode.showTree(tn);
    }
}
